package com.lt.lumentracks.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Slf4j
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory, ObjectMapper om) {

        RedisTemplate rt = new RedisTemplate<>();
        rt.setConnectionFactory(factory); //设置redis的连接工厂对象

        rt.setKeySerializer(new StringRedisSerializer()); // 设置redis key的序列化器

        // 使用 Jackson 实现 JSON 序列化
        GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(om);
        rt.setValueSerializer(jsonSerializer);
        rt.setHashValueSerializer(jsonSerializer); // 如果要操作 Hash 类型，则最好设置 HashValue 的序列化器


        // 尝试执行ping命令
        String host = "unknown"; // 获取 主机号
        int port = -1; // 获取 端口号
        try {
            // 使用反射获取配置
            Object configuration = factory.getClass().getMethod("getStandaloneConfiguration").invoke(factory);
            if (configuration instanceof RedisStandaloneConfiguration) {
                host = ((RedisStandaloneConfiguration) configuration).getHostName();
                port = ((RedisStandaloneConfiguration) configuration).getPort();
            }

            String result = rt.getConnectionFactory().getConnection().ping(); // 测试连接
            if ("PONG".equalsIgnoreCase(result)) {
                log.info("✅ Redis连接成功：{}:{}", host, port);
            } else {
                log.error("❌ Redis连接异常,{}:{}，返回信息: {}", host, port , result);
            }
        } catch (Exception e) {
            log.error("❌ Redis连接失败,{}:{}，错误信息: {}", host, port, e.getMessage());
            log.error("请检查Redis服务是否可用");
        }


        return rt;
    }
}